package com.jian.socks5.tcp.handler;

import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.handler.codec.socksx.v5.Socks5CommandRequestDecoder;
import io.netty.handler.codec.socksx.v5.Socks5InitialRequestDecoder;
import io.netty.handler.codec.socksx.v5.Socks5ServerEncoder;
import io.netty.util.concurrent.EventExecutorGroup;

public class ServerChannelInitializer extends ChannelInitializer<Channel> {

    private EventExecutorGroup eventExecutors;

    private static ServerChannelInitializer serverChannelInitializer;

    public static ServerChannelInitializer getServerChannelInitializerInstan(EventExecutorGroup eventExecutors){
        if (serverChannelInitializer == null) {
            serverChannelInitializer = new ServerChannelInitializer(eventExecutors);
        }
        return serverChannelInitializer;
    }

    public ServerChannelInitializer(EventExecutorGroup eventExecutors) {
        this.eventExecutors = eventExecutors;
    }


    @Override
    protected void initChannel(Channel ch) {
        long l = System.nanoTime();
        ChannelPipeline pipeline = ch.pipeline();

        pipeline.addLast(eventExecutors, Socks5ServerEncoder.DEFAULT); //编码消息
        pipeline.addLast(eventExecutors, new Socks5InitialRequestDecoder());
        pipeline.addLast(eventExecutors, new Socks5InitialReuqestHandler()); //初始化 返回是否需要认证等消息
        pipeline.addLast(eventExecutors, new Socks5CommandRequestDecoder());
        pipeline.addLast(eventExecutors, new Socks5CommandRequestHandler()); //处理消息

        l = System.nanoTime() - l;
        System.out.println("耗时:" + l + "mss");
    }
}
